package com.io.example.demoparent.ES.es;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.io.example.demoparent.ES.entity.User;
import com.io.example.demoparent.ES.util.ESUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/*
     添加文档
 */
public class ES_Index_Insert {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = ESUtil.esRestClient( );
        IndexRequest indexRequest = new IndexRequest( );
        indexRequest.index("user") .id("1001");

        User user = User.builder( ).userName("李四").age(100).gender("男").build( );
        //插入ES的数据必须是JSON格式
        ObjectMapper objectMapper = new ObjectMapper( );
        String userJSON = objectMapper.writeValueAsString(user);

        indexRequest.source(userJSON, XContentType.JSON );

        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println("response.getResult() = " + response.getResult( ));

        client.close();
    }
}
